﻿namespace Mydra.IsdbTools
{
    using System;
    using System.IO;
    using System.Text;

    //Courtesy of http://trac.opensubtitles.org/projects/opensubtitles/wiki/HashSourceCodes#C2
    public static class IsdbHashesHelper 
    {
   

        public static byte[] ComputeMovieHash(string filename)
        {
            byte[] result;
            using (Stream input = File.OpenRead(filename))
            {
                result = ComputeMovieHash(input);
            }
            return result;
        }

        /// <summary>
        /// Computes the movie hash.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <remarks>The responsibility for closing the provided stream is left to the caller.</remarks>
        /// <returns>A byte-array representation of the hash.</returns>
        public static byte[] ComputeMovieHash(Stream input)
        {
            long lhash, streamsize;
            streamsize = input.Length;
            lhash = streamsize;

            long i = 0;
            byte[] buffer = new byte[sizeof(long)];
            while (i < 65536 / sizeof(long) && (input.Read(buffer, 0, sizeof(long)) > 0))
            {
                i++;
                lhash += BitConverter.ToInt64(buffer, 0);
            }

            input.Position = Math.Max(0, streamsize - 65536);
            i = 0;
            while (i < 65536 / sizeof(long) && (input.Read(buffer, 0, sizeof(long)) > 0))
            {
                i++;
                lhash += BitConverter.ToInt64(buffer, 0);
            }
            
            byte[] result = BitConverter.GetBytes(lhash);
            Array.Reverse(result);
            return result;
        }

        /// <summary>
        /// Converts a byte array hash to the string-hexadecimal representation.
        /// </summary>
        /// <param name="bytes">The bytes.</param>
        /// <returns>The string-hexadecimal representation.</returns>
        public static string ToHexadecimal(byte[] bytes)
        {
            StringBuilder hexBuilder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                hexBuilder.Append(bytes[i].ToString("x2"));
            }

            return hexBuilder.ToString();
        }      
    }

}
